package com.lovebugs;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import freemarker.template.Configuration;

import freemarker.template.DefaultObjectWrapper;

import freemarker.template.Template;

import freemarker.template.TemplateException;

public class AbstractTag extends TagSupport {

	private OgnlContext ognlContext = new OgnlContext();

	private UIBean component;

	public String path = "/template"; // 可从系统中加载

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * A.Tag.SKIP_BODY：表示?>…之间的内容被忽略 B.Tag.EVAL_BODY_INCLUDE：表示标签之间的内容被正常执行
	 */
	public UIBean getUIBean(OgnlContext ognlContext, HttpServletRequest req,
			HttpServletResponse resp) {
		return null;
	}

	public void populateParams() {
	}

	public int doStartTag() throws JspException {

		HttpServletRequest req = (HttpServletRequest) this.pageContext
				.getRequest();
		HttpServletResponse resp = (HttpServletResponse) this.pageContext
				.getResponse();
		/* 获取UI组件,并填充参数 */
		this.component = this.getUIBean(ognlContext, req, resp);
		this.populateParams();
		Tag pTag = this.getParent();
		/* 如果有父标签，并且父标签是同类标签，那么把子标签放置到父标签内 */
		if (null != pTag && pTag instanceof AbstractTag) {
			AbstractTag tag = (AbstractTag) pTag;
			tag.getComponent().addComponent(this.component);
		} else {
			this.getOgnlContext().setRoot(this.component);
		}
		return Tag.EVAL_BODY_INCLUDE;
	}

	/**
	 * A.Tag.SKIP_PAGE：表示立刻停止执行网页，网页上未处理的静态内容和JSP程序均被忽略任何已有的输出内容立刻返回到客户的浏览器上。
	 * B.Tag_EVAL_PAGE：表示按照正常的流程继续执行JSP网页
	 * 
	 * @throws IOException
	 */
	public int doEndTag() throws JspException {

		/* 最终输出,当没有父标签或者父标签非同类标签，那么输出 */
		if (null == this.getParent()
				|| !(this.getParent() instanceof AbstractTag)) {
			// 获取路径模板,,freemarker转化
			String ftlname = this.component.getTemplate() + ".ftl";
			try {
				Template temp = OgnlContext.TEMPLATE_CFG.getTemplate(ftlname);
				Writer out = this.pageContext.getOut();
				temp.process(this.getOgnlContext().get("root"), out);
				out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return Tag.EVAL_BODY_INCLUDE;
	}

	public OgnlContext getOgnlContext() {
		return ognlContext;
	}

	public void setOgnlContext(OgnlContext ognlContext) {
		this.ognlContext = ognlContext;
	}

	public UIBean getComponent() {
		return component;
	}

	public void setComponent(UIBean component) {
		this.component = component;
	}
}
